package com.komorebi.security;

import com.komorebi.entity.SysUser;
import com.komorebi.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
@Slf4j
@Component
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    SysUserService userService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("开始登陆验证，用户名为: {}",username);
        SysUser user = userService.getByUserName(username);
        if(user == null){
            log.info("用户名或密码不正确");
            throw new UsernameNotFoundException("用户名或密码不正确");
        }
        //UserDetails是接口，User是它的一个实现类
        //将用户密码告诉springSecurity
        //剩下的认证 就由框架Security帮我们完成

        return new User(user.getUsername(),user.getPassword(),getUserAuthority(user.getId()));
    }
    /*获取用户权限信息（角色，菜单权限）
    * */
    public List<GrantedAuthority> getUserAuthority(Long userId){
        //返回拥有角色和权限，逗号分隔
        String authority = userService.getUserAuthority(userId);
        //AuthorityUtils.commaSeparatedStringToAuthorityList将逗号分隔的字符串转为权限列表
        return AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
    }
}
